// SPDX-License-Identifier: GPL-2.0
/*
 * BiscuitOS MISC DD on Userspace
 *
 * (C) 2020.10.06 <buddy.zhang@aliyun.com>
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/ioctl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/mman.h>

struct BiscuitOS_hmm_cmd {
	unsigned long addr;
	unsigned long ptr;
	unsigned long npages;
} hmm_cmd;

#define HMM_READ	_IOWR('H', 0x00, struct BiscuitOS_hmm_cmd)
#define DEV_PATH	"/dev/BiscuitOS-GPU-VRAM-BAR"
#define errExit(msg)	do { perror(msg); exit(EXIT_FAILURE); } while (0)
#define MAP_SIZE	0x200000

int main()
{
	void *buffer;
	int fd;

	/* OPEN DEVICE */
	fd = open(DEV_PATH, O_RDWR);
	if (fd < 0)
		errExit("OPEN ERROR");

	/* ALLOC ANONYMOUS MEMORY */
	buffer = mmap(NULL, MAP_SIZE,
		      PROT_READ | PROT_WRITE,
		      MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE,
		      -1,
		      0);
	if (buffer == MAP_FAILED)
		errExit("MMAP ERROR");

	/* HMM READ */
	hmm_cmd.addr = (unsigned long)buffer;
	ioctl(fd, HMM_READ, &hmm_cmd);

	close(fd);

	return 0;
}
